package org.mtmi.ui.controls;

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.mtmi.io.IControlIO;
import org.mtmi.io.controls.SKnobIO;
import org.mtmi.ui.IMG;
import org.mtmi.ui.layouts.LayoutData;
import org.mtmi.ui.scenes.Scene;

/**
 * Skinnable Knob, made with 2 images: background, and centered rotated image for knob.
 * <p>
 * Knob image should be draw at 0 degree angle (3 o'clock), it's rotated around center of background image.
 * <p>
 * To change Knob angle bounds, overriding getAngleVMin() and getDAngle().
 */
public class SKnob extends AbstractKnob
{
	
	private String s_img_back, s_img_knob;
	private Image img_back, img_knob;

	public SKnob( Scene scene, int flags ) {
		super( scene, flags );
	}
	
	/** default values are: 0 in range 0..100 */
	public SKnob( Scene scene, String iback, String iknob,  int _flags ) {
		super( scene, 0,0,100, _flags );
		setImages( iback, iknob );
	}
	
	@Override
	public Object getAdapter( Class<?> clazz, Object arg ) {
		if( clazz == IControlIO.class ) {
			return new SKnobIO();
		}
		return super.getAdapter( clazz, arg );
	}
	
	public String getBackgroundImage() { return s_img_back; }
	public String getKnobImage() { return s_img_knob; }
	
	public void setImages( String iback, String iknob ) {
		s_img_back = iback;
		s_img_knob = iknob;
		img_back = IMG.Get( s_img_back );
		img_knob = IMG.Get( s_img_knob );
		setSize( computeSize( null ) );
	}
	
	@Override
	public Point computeSize( LayoutData l ) {
		Rectangle ri = img_back.getBounds();
		return new Point( ri.width, ri.height );
		//note: need to check if pixel at image is transparent or not ?? ... what and see if needed
	}
	
	
	@Override
	public void paint(GC gc)
	{
		Rectangle ri = img_back.getBounds();
		
		float fx = size.x/(float)ri.width;
		float fy = size.y/(float)ri.height;
        gc.drawImage( img_back, 0,0,ri.width,ri.height, location.x,location.y,size.x,size.y );
		
        //knob:
        ri = img_knob.getBounds();
		
        int cx = getCX();
		int cy = getCY();
		
		int da = getAngleVMin() + getAngle();
		Transform t = new Transform( gc.getDevice() );
		t.translate( cx, cy );
		t.scale( fx, fy );
		t.rotate( -(float)da );
		
		gc.setTransform( t );
		gc.drawImage( img_knob,  -ri.width/2, -ri.height/2 );
		gc.setTransform( null );
		
		t.dispose();
	}
	
}
